const XMLHttpRequest = require("xmlhttprequest");
const createError = require("../axios/lib/core/createError");
const buildURL = require("../axios/lib/helpers/buildURL");
const parseHeaders = require("../axios/lib/helpers/parseHeaders");
const utils = require("../axios/lib/utils");
const xhrHttp = function (config) {
  return new Promise(function (resolve, reject) {
    // 定义数据
    const requestData = config.data;
    // 定义头部信息
    const requestHeaders = config.headers;
    // 声明xhr
    let request = new XMLHttpRequest.XMLHttpRequest();
    // 调用open方法
    request.open(
      config.method.toUpperCase(),
      buildURL(config.url, config.params, config.paramsSerializer),
      true
    );
    // 事件监听 判断是否为4
    request.onreadystatechange = function () {
      console.log(request, "request");
      if (!request || request.readyState !== 4) {
        return;
      }
      const responseHeaders =
        "getAllResponseHeaders" in request
          ? parseHeaders(request.getAllResponseHeaders())
          : null;
      const responseData = request.responseText;
      const response = {
        data: responseData,
        config: config,
        request: request,
        headers: responseHeaders,
        status: request.status === 1223 ? 204 : request.status,
        statusText: request.status === 1223 ? "No Content" : request.statusText,
      };
      resolve(response);
      request = null;
    };

    request.onerror = function () {
      reject(createError("Network Error", config, null, request));
    };
    if ("setRequestHeader" in request) {
      utils.forEach(requestHeaders, function setRequestHeader(val, key) {
        if (
          typeof requestData === "undefined" &&
          key.toLowerCase() === "content-type"
        ) {
          // Remove Content-Type if data is undefined
          delete requestHeaders[key];
        } else {
          // Otherwise add header to the request
          request.setRequestHeader(key, val);
        }
      });
    }
    request.send(requestData);
  });
};

module.exports = xhrHttp;
